package org.jeecg.modules.engineering.util;

import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.PasswordUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import	java.security.InvalidKeyException;
import	java.security.NoSuchAlgorithmException;

public	class	HMACSHAHelper	{
    private	static	final	String	HMAC_SHA1= "HmacSHA1";
    /**
     * 生成签名数据
     *	@param	data 待加密的数据
     *  @param	key	 加密使用的 key 这里为 api_key 这里为 secret_ke53
     *	@return	生成十六进制字符串
     **/
    public	static	String	getSHA1Signature(byte[]	data,	byte[]	key)	{

        SecretKeySpec signingKey = new	SecretKeySpec(key,	HMAC_SHA1);
        Mac mac	= null;
        try {
            mac = Mac.getInstance(HMAC_SHA1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new JeecgBootException(e.toString());
        }
        try {
            mac.init(signingKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new JeecgBootException(e.toString());
        }
        byte[]	rawHmac	= mac.doFinal(data);
        return	bytesToHexString(rawHmac);
    }

    private static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
